import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Table, message, Tabs, Popconfirm, Icon } from 'antd';

const TabPane = Tabs.TabPane;

import { SelectDepOrPerson } from 'components/index'
import RSService from 'containers/setting/role-setting/role-setting.service'
import 'styles/setting/role-setting/booking-role/booking-role.scss'
import ResizeTable from "components/resize-table";

class RoleSettingBooking extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      tab: 'manager',
      columns: [
        {title: messages('common.sequence'), dataIndex: 'index', width: '10%', render: (value, record, index) =>
          this.state.pageSize * this.state.page + index + 1},
        {title: messages('setting.key886'/*工号*/), dataIndex: 'employeeID'},
        {title: messages('setting.key887'/*姓名*/), dataIndex: 'fullName'},
        {title: messages('setting.key888'/*部门*/), dataIndex: 'department', render: value => value.name},
        {title: messages('setting.key891'/*订票类型*/), dataIndex: 'status', render: value => messages('setting.key892'/*机票*/)}
      ],
      data: [],
      pagination: {
        total: 0
      },
      page: 0,
      pageSize: 10,
    };
  }

  componentDidMount() {
    let columns = this.state.columns;
    this.props.tenantMode && columns.push(
      {title: messages('common.operation'), dataIndex: 'userOID', width: '10%', render: value => (
        <Popconfirm onConfirm={() => this.handleDelete(value)} title={messages('common.confirm.delete')}>
          <a onClick={e => {e.preventDefault();e.stopPropagation()}}>{messages('common.delete')}</a>
        </Popconfirm>
      )}
    );
    this.setState({ columns }, () => {
      this.getList()
    })
  }

  getList = () => {
    const { tab, page, pageSize } = this.state;
    let roleName = tab === 'manager' ? 'ROLE_COMPANY_BOOK_ADMIN' : 'ROLE_COMPANY_BOOK';
    let params = {
      page, size: pageSize
    };
    this.setState({ loading: true });
    RSService.getRoleUserListByRoleName(roleName, params).then(res => {
      this.setState({
        loading: false,
        data: res.data || [],
        pagination: {
          total: Number(res.headers['x-total-count']) || 0,
          onChange: this.onChangePager,
          current: this.state.page + 1
        }
      })
    }).catch(() => {
      this.setState({ loading: false })
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({ page: page - 1 }, () => {
        this.getList()
      })
  };

  onChangeTabs = (tab) => {
    this.setState({ tab }, () => {
      this.getList()
    })
  };

  handleAdd = (result) => {
    let authorityName = this.state.tab === 'manager' ? 'ROLE_COMPANY_BOOK_ADMIN' : 'ROLE_COMPANY_BOOK';
    let userOIDs = [];
    result.map(item => {
      userOIDs.push(item.userOID)
    });
    let params = {authorityName, userOIDs};
    this.setState({ loading: true });
    RSService.addRoleUser(params).then(() => {
      message.success(messages('common.operate.success'));
      this.getList()
    })
  };

  handleDelete = (OID) => {
    let authorityName = this.state.tab === 'manager' ? 'ROLE_COMPANY_BOOK_ADMIN' : 'ROLE_COMPANY_BOOK';
    let params = {
      authorityName,
      userOIDs: [OID]
    };
    RSService.deleteRoleUser(params).then(() => {
      this.getList()
    })
  };

  goBack = () => {
    this.context.router.goBack()
  };

  render() {
    const { loading, tab, columns, data, pagination } = this.state;
    const {tenantMode} = this.props;
    return (
      <div className="setting-role-setting-booking">
        <Tabs onChange={this.onChangeTabs} activeKey={tab}>
          <TabPane tab={messages('setting.key893'/*订票管理员*/)} key='manager'/>
          <TabPane tab={messages('setting.key894'/*订票专员*/)} key='commissioner'/>
        </Tabs>
        {tenantMode && (
          <div className="table-header">
            <div className="table-header-buttons">
              <SelectDepOrPerson buttonType="primary"
                                 title={messages('common.add')}
                                 onlyPerson={true}
                                 externalParams={{bookingRoleList: data}}
                                 onConfirm={this.handleAdd}/>
            </div>
            <div className="table-header-title">{messages('common.total', {total: pagination.total})}</div>
          </div>
        )}
        <ResizeTable
          loading={loading}
          columns={columns}
          dataSource={data}
          pagination={pagination}
          size="middle"
          bordered
          rowKey={record=>record.id}
        />
        <a className="back" onClick={this.goBack}>
          <Icon type="rollback" style={{marginRight: 5}}/>
          {messages('common.back')}
        </a>
      </div>
    )
  }
}
RoleSettingBooking.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
  }
}

export default connect(mapStateToProps)(RoleSettingBooking);
